package LinkedListDemo;

public class LinkedList {

    Node head = new Node(0);
    int size;

    static class Node {
        int val;
        Node next;

        public Node(int val) {
            this.val = val;
            this.next = null;
        }
    }

    public void add(int val) {

        Node curr = head;
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = new Node(val);
        size++;
    }

    public void add2(int val, int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("非法");
        }

        Node curr = head;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }

        Node node = new Node(val);
        node.next = curr.next;
        curr.next = node;
        size++;
    }

    public int remove(int index) {
        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }
        Node curr = head;
        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }
        int result = curr.next.val;

        curr.next = curr.next.next;
        size--;
        return result;
    }

    public int get(int index) {
        Node curr = head;

        if (index < 0 || index > size - 1) {
            throw new IndexOutOfBoundsException("非法");
        }

        for (int i = 0; i < index; i++) {
            curr = curr.next;
        }

        int val = curr.next.val;
        return val;
    }

    public void print() {
        Node curr = head.next;
        while (curr != null) {
            System.out.println(curr.val + " ");
            curr = curr.next;
        }
        System.out.println();
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();

        Node curr = head.next;
        while (curr != null) {
            sb.append(curr.val).append(" ");
            curr = curr.next;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(1);
        list.add(3);
        list.add2(4, 1);

        int remove = list.remove(1);
        System.out.println(remove);
        System.out.println("======================");
        list.print();
        int i = list.get(0);
        System.out.println(i);
        //String s = list.toString();
        // System.out.println(s);
    }
}
